local xuanfu = fk.CreateSkill {
  name = "lingling__xuanfu",
}

Fk:loadTranslationTable{
  ["lingling__xuanfu"] = "旋复",
  [":lingling__xuanfu"] = "当你点数递增使用牌后，若你攻击范围小于3，你可以摸一张牌，本回合攻击范围+1。当你点数递减使用牌后，若你攻击范围大于1，"..
  "你可以重铸一张牌，本回合攻击范围-1。",

  ["@lingling__xuanfu"] = "旋复",
  ["#lingling__xuanfu-draw"] = "旋复：你可以摸一张牌，本回合攻击范围+1",
  ["#lingling__xuanfu-recast"] = "旋复：你可以重铸一张牌，本回合攻击范围-1",
}

xuanfu:addEffect(fk.CardUsing, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    if target == player and player:hasSkill(xuanfu.name) and data.extra_data then
      if data.extra_data.lingling__xuanfu1 then
        return player:getAttackRange() < 3
      elseif data.extra_data.lingling__xuanfu2 then
        return player:getAttackRange() > 1 and not player:isNude()
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    if data.extra_data.lingling__xuanfu1 then
      return room:askToSkillInvoke(player, {
        skill_name = xuanfu.name,
        prompt = "#lingling__xuanfu-draw",
      })
    elseif data.extra_data.lingling__xuanfu2 then
      local cards = room:askToCards(player, {
        min_num = 1,
        max_num = 1,
        include_equip = true,
        skill_name = xuanfu.name,
        prompt = "#lingling__xuanfu-recast",
        cancelable = true,
      })
      if #cards > 0 then
        event:setCostData(self, {cards = cards})
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if data.extra_data.lingling__xuanfu1 then
      room:setPlayerMark(player, "lingling__xuanfu-turn", player:getMark("lingling__xuanfu-turn") + 1)
      player:drawCards(1, xuanfu.name)
    else
      room:setPlayerMark(player, "lingling__xuanfu-turn", player:getMark("lingling__xuanfu-turn") - 1)
      room:recastCard(event:getCostData(self).cards, player, xuanfu.name)
    end
  end,

  can_refresh = function (self, event, target, player, data)
    return target == player and player:hasSkill(xuanfu.name, true)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    data.extra_data = data.extra_data or {}
    local mark = player:getMark("@lingling__xuanfu")
    if mark ~= 0 and data.card.number ~= mark and data.card.number ~= 0 then
      if data.card.number > mark then
        data.extra_data.lingling__xuanfu1 = true
      else
        data.extra_data.lingling__xuanfu2 = true
      end
    end
    room:setPlayerMark(player, "@lingling__xuanfu", data.card.number)
  end,
})

xuanfu:addEffect("atkrange", {
  correct_func = function (self, from, to)
    return from:getMark("lingling__xuanfu-turn")
  end,
})

xuanfu:addLoseEffect(function (self, player, is_death)
  player.room:setPlayerMark(player, "@lingling__xuanfu", 0)
end)

return xuanfu
